package com.yxy.controller.service;


import com.google.common.collect.Maps;
import com.yxy.common.Const;
import com.yxy.common.ServerResponse;
import com.yxy.dto.ClientContentModel;
import com.yxy.entity.ClientContent;
import com.yxy.entity.User;
import com.yxy.service.ClientContentService;
import com.yxy.service.IFileService;
import com.yxy.util.DateUtils;
import com.yxy.util.PropertiesUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * ClientContentController控制器类
 * ClientContent
 * ClientContent
 * ClientContent
 * ClientContent
 *
 * @version <pre>
 * Author	Version		Date		Changes
 * 邓文俊    1.0  2018-01-11 17:40:11 Created
 *  </pre>
 * @since 1.
 */
@Controller
@RequestMapping("/service/clientContents/")
public class ClientContentController {

    public Logger logger = LoggerFactory.getLogger(ClientContentController.class);

    @Autowired
    private ClientContentService clientContentService;

    @Autowired
    private IFileService iFileService;


    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<ClientContentModel> cerate(@RequestBody ClientContentModel clientContentModel,HttpServletRequest request){
        ClientContent clientContent = modelToEntity(clientContentModel);
        if(clientContent!=null){
            setTemplateDateAndUser(clientContent,request);
            if(clientContentService.create(clientContent)){
                return ServerResponse.createBySuccessMessage("添加成功");
            }
        }
        return ServerResponse.createByErrorMessage("操作失败,请重试");
    }

    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<List<ClientContentModel>> list() throws Exception{
        List<ClientContentModel> clientContentModels= new ArrayList<ClientContentModel>();
        List<ClientContent> clientContentList = clientContentService.findAll();
        if(clientContentList!=null && clientContentList.size()>0){
            for (ClientContent clientContent:clientContentList) {
                ClientContentModel clientContentModel = entityToModel(clientContent);
                clientContentModels.add(clientContentModel);
            }
        }
        return ServerResponse.createBySuccess("查询成功",clientContentModels);
    }

    //删除
    @RequestMapping("delete")
    @ResponseBody
    public ServerResponse delete(Integer id,HttpServletRequest request) throws Exception{
        ClientContent clientContent = new ClientContent();
        clientContent.setId(id);
        setTemplateDateAndUser(clientContent,request);
        if(clientContentService.delete(clientContent)){
            return ServerResponse.createBySuccessMessage("删除成功");
        }
        return ServerResponse.createByErrorMessage("操作失败，请重试！");
    }


    @RequestMapping(value = "findLikeList", method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse findLikeList(String title) throws Exception{
        ClientContent clientContent = new ClientContent();
        clientContent.setBannerTitle(title);
        List<ClientContent> clientContentList = clientContentService.findLikeList(clientContent);
        List<ClientContentModel> contentModels =new ArrayList<ClientContentModel>();
        if (clientContentList!=null && clientContentList.size()>0){
            for (ClientContent c:clientContentList) {
                ClientContentModel model = entityToModel(c);
                contentModels.add(model);
            }

        }
        return ServerResponse.createBySuccess("查询成功",contentModels);
    }

    //查询用户
    @RequestMapping("findOne")
    @ResponseBody
    public ServerResponse findOne(Integer id)throws Exception{
        ClientContent clientContent = clientContentService.findByPK(id);
        if (clientContent!=null){
            ClientContentModel clientContentModel = entityToModel(clientContent);
            return ServerResponse.createBySuccess("查询成功",clientContentModel);
        }
        return ServerResponse.createByErrorMessage("操作失败，请重试！");
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<ClientContentModel> update(@RequestBody ClientContentModel clientContentModel,HttpServletRequest request){
        ClientContent clientContent = modelToEntity(clientContentModel);

        setTemplateDateAndUser(clientContent,request);
        if(clientContentService.update(clientContent)){
            return ServerResponse.createBySuccessMessage("操作成功!");
        }
        return ServerResponse.createByErrorMessage("操作失败,请重试!");
    }


    @RequestMapping("upload_img")
    @ResponseBody
    public ServerResponse upload(HttpSession session, @RequestParam(value = "banner_img",required = false) MultipartFile file,String oldFileName, HttpServletRequest request) {
        logger.debug(oldFileName);
        User user = (User) session.getAttribute(Const.ADMIN_USER);
        if (user!=null){
            String path = request.getSession().getServletContext().getRealPath("upload");
            String targetFileName = iFileService.upload(file,path,oldFileName,Const.IMG_BANNER);
            String url = PropertiesUtil.getProperty("ftp.server.http.prefix")+"banner/"+targetFileName;

            Map fileMap = Maps.newHashMap();
            fileMap.put("uri",targetFileName);
            fileMap.put("url",url);
            return ServerResponse.createBySuccess(fileMap);
        }
        return ServerResponse.createByErrorMessage("用户未登录");

    }





        /**
         * 统一设置 Date 和 修改用户
         *
         * @param entity
         */
    private void setTemplateDateAndUser(ClientContent entity, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute(Const.ADMIN_USER);

        if (entity == null) {
            logger.error("ERR:Date set error.");
            return;
        }
        if (entity.getId() == null && entity.getCreateDatetime() == null) {
            //如果id为空， 就是新建
            entity.setCreateDatetime(new Date());
            entity.setCreateBy(user.getUsername());
        } else {

            if (entity.getUpdateDatetime() == null) {
                entity.setUpdateDatetime(new Date());
            }
            if (entity.getUpdateBy() == null && user != null) {
                entity.setUpdateBy(user.getUsername());
            }
        }
    }


    /**
     * 复制 数据库端 Entity 到 前端 Entity
     *
     * @param entity 数据库端 Entity
     * @return model  前端 Model
     */
    public ClientContentModel entityToModel(ClientContent entity) throws Exception {
        if (entity == null) {
            return new ClientContentModel();
        }
        ClientContentModel model = new ClientContentModel();
        if (entity.getCreateDatetime() != null) {
            model.setCreateDatetime(DateUtils.formatDateTime(entity.getCreateDatetime()));
        }else {
            model.setCreateDatetime("无");
        }
        if (entity.getUpdateDatetime() != null) {
            model.setUpdateDatetime(DateUtils.formatDateTime(entity.getUpdateDatetime()));
        }else {
            model.setUpdateDatetime("无");
        }
        if (entity.getDelFlag() != null) {
            model.setDelFlag(String.valueOf(entity.getDelFlag()));
        }
        if (entity.getId() != null) {
            model.setId(String.valueOf(entity.getId()));
        }
        if (entity.getYxyClientContentExtend3() != null) {
            model.setYxyClientContentExtend3(String.valueOf(entity.getYxyClientContentExtend3()));
        }
        if (entity.getYxyClientContentExtend4() != null) {
            model.setYxyClientContentExtend4(String.valueOf(entity.getYxyClientContentExtend4()));
        }
        if (StringUtils.isNotBlank(entity.getBannerImg())) {
            model.setBannerImg(String.valueOf(entity.getBannerImg()));
        }
        if (StringUtils.isNotBlank(entity.getBannerTitle())) {
            model.setBannerTitle(String.valueOf(entity.getBannerTitle()));
        }
        if (StringUtils.isNotBlank(entity.getBannerUrl())) {
            model.setBannerUrl(String.valueOf(entity.getBannerUrl()));
        }
        if (StringUtils.isNotBlank(entity.getUpdateBy())) {
            model.setUpdateBy(String.valueOf(entity.getUpdateBy()));
        }else {
            model.setUpdateBy("无");
        }
        if (StringUtils.isNotBlank(entity.getCreateBy())) {
            model.setCreateBy(String.valueOf(entity.getCreateBy()));
        }else {
            model.setCreateBy("无");
        }
        if (StringUtils.isNotBlank(entity.getYxyClientContentExtend1())) {
            model.setYxyClientContentExtend1(String.valueOf(entity.getYxyClientContentExtend1()));
        }
        if (StringUtils.isNotBlank(entity.getYxyClientContentExtend2())) {
            model.setYxyClientContentExtend2(String.valueOf(entity.getYxyClientContentExtend2()));
        }
        return model;
    }

    /**
     * 复制前端 Model 到 数据库端 Entity
     *
     * @param model 前端 Model
     * @return entity 数据库端 Entity
     */
    public ClientContent modelToEntity(ClientContentModel model) {
        if (model == null) {
            return new ClientContent();
        }
        ClientContent entity = new ClientContent();
        if (StringUtils.isNotBlank(model.getCreateDatetime())) {
            entity.setCreateDatetime(DateUtils.parseDate(model.getCreateDatetime()));
        }
        if (StringUtils.isNotBlank(model.getUpdateDatetime())) {
            entity.setUpdateDatetime(DateUtils.parseDate(model.getUpdateDatetime()));
        }
        if (StringUtils.isNotBlank(model.getDelFlag())) {
            entity.setDelFlag(Integer.parseInt(model.getDelFlag()));
        }
        if (StringUtils.isNotBlank(model.getId())) {
            entity.setId(Integer.parseInt(model.getId()));
        }
        if (StringUtils.isNotBlank(model.getYxyClientContentExtend3())) {
            entity.setYxyClientContentExtend3(Integer.parseInt(model.getYxyClientContentExtend3()));
        }
        if (StringUtils.isNotBlank(model.getYxyClientContentExtend4())) {
            entity.setYxyClientContentExtend4(Integer.parseInt(model.getYxyClientContentExtend4()));
        }
        entity.setBannerImg(model.getBannerImg());
        entity.setBannerTitle(model.getBannerTitle());
        entity.setBannerUrl(model.getBannerUrl());
        entity.setUpdateBy(model.getUpdateBy());
        entity.setCreateBy(model.getCreateBy());
        entity.setYxyClientContentExtend1(model.getYxyClientContentExtend1());
        entity.setYxyClientContentExtend2(model.getYxyClientContentExtend2());

        return entity;
    }

}